<?php
//if ($_SESSION['memberID']!=1 || $_SESSION['sid']!=1
//    || empty($_POST['ordernum']) ) {
//    Response('非法操作');
//}
include("/var/www/html/new/com.inc.php");
include("/var/www/html/new/d/class/SoapInit.class.php");

define('LOG_REQUEST', '/var/www/html/new/d/logs/refund/req_'.date('ymd').'.txt');
define('LOG_NAME', '/var/www/html/new/d/logs/refund/err_'.date('ymd').'.txt');
define('LOG_NAME_OK', '/var/www/html/new/d/logs/refund/ok_'.date('ymd').'.txt');
define('ACTION_MONEY_ADD',0);
define('ACTION_MONEY_CUT',1);
use \LaneWeChat\Core\TemplateMessage;

LogRefund(json_encode($_GET), LOG_REQUEST);


//if (empty($_GET['ordernum'])) {
//    LogRefund('订单号不能为空',LOG_NAME);
//    Response('订单号不能为空');
//}

//$comp = md5(md5($_GET['ordernum']).md5(strrev($_GET['ordernum'])));

//$comp = md5(md5(md5($_GET['ordernum'])));
//if (empty($_GET['auth']) || $_GET['auth']!=$comp) {
//    LogRefund('身份验证失败',LOG_NAME);
//    Response("身份验证失败");
//}
/**
 * 计算订单取消费用，是根据票数退款哦~
 *
 * @author GuangPeng Chen
 * @param Int $tid      门票ID
 * @param Int $price    价格（单位分）
 * @param string $beginTime     订单游玩时间
 * @return array|bool|int       成功返回退票手续费，金额分
 */
function count_cost_fee( $tid, $price, $beginTime)
{
    $play_date = strtotime( $beginTime . ' 00:00:00');
    $today     = strtotime(date('Y-m-d 00:00:00'));
    $day_diff  = ($play_date - $today) / 86400;//距离游玩时间的天数
    //取消费用,cancel_cost,reb=>手续费,reb_type=>手续费类型0%，1固定金额

    //使用cancel_cost字段收取手续费的供应商，目前（2014年12月19日）只有云顶
//    $use_cancel_cost = array(
//        7133,7134,7135,7136,
//    );
    //reb_type
    $sql = "SELECT id,cancel_cost,reb,reb_type,apply_did FROM uu_jq_ticket"
        . " WHERE id=$tid LIMIT 1";
    $GLOBALS['le']->query($sql);
    $total_fee    = 0;//取消费用，考虑到后期有可能订单里面的票取消费用计算方式不一致
    while($row    = $GLOBALS['le']->fetch_assoc()) {
        //in_array($row['apply_did'], $use_cancel_cost) &&
        if ($row['cancel_cost']) {
//            if (!$row['cancel_cost']) continue;
            $cancel_cost = $row['cancel_cost'];
        }
        elseif ($row['reb']>0) {
            if ($row['reb_type']==1) {
                $total_fee += $row['reb'];
            }
            else {
                //按百分比收取手续费
                $total_fee += ($row['reb'] * $price) / 100;
            }
        }
    }
    if (isset($cancel_cost) && !empty($cancel_cost)) {
        //取消费用一维数组 array('提前天数'=>'百分比')
        $cancel_cost_arr = json_encode($cancel_cost, true);
        $day_arr         = array_keys($cancel_cost_arr);
        sort($day_arr);
        $min_day         = min($day_arr);
        $max_day         = max($day_arr);
        if ($day_diff <= $min_day) {
            $fee = $cancel_cost_arr[$min_day];
        }
        elseif ($day_diff >= $max_day) {
            $fee = 0;
        } else {
            foreach ($day_arr as $key=>$val) {
                if ($day_diff >= $val && $day_diff <= $day_arr[$key+1]) {
                    $fee = $day_arr[$key+1];
                    break;
                }
            }
        }
        $total_fee += ($fee * $price) / 100  ;
    }
    return $total_fee;
}


function count_cost_fee_dev( $tid, $price, $beginTime)
{
    $play_date    = strtotime( $beginTime . ' 00:00:00');
    $now_timestamp     = $_SERVER['REQUEST_TIME'];
    $minute_diff  = $play_date - $now_timestamp;//距离游玩时间的分钟数
    //取消费用,cancel_cost,reb=>手续费,reb_type=>手续费类型0%，1固定金额

    $sql = "SELECT id,cancel_cost,reb,reb_type,apply_did FROM uu_jq_ticket"
        . " WHERE id=$tid LIMIT 1";
    $GLOBALS['le']->query($sql);
    $total_fee    = 0;//取消费用，考虑到后期有可能订单里面的票取消费用计算方式不一致
    while($row    = $GLOBALS['le']->fetch_assoc()) {
        //in_array($row['apply_did'], $use_cancel_cost) &&
        if ($row['cancel_cost']) {
            $cancel_cost = $row['cancel_cost'];
        }
        elseif ($row['reb']>0) {
            if ($row['reb_type']==1) {
                $total_fee += $row['reb'];
            }
            else {
                //按百分比收取手续费
                $total_fee += ($row['reb'] * $price) / 100;
            }
        }
    }
    echo 'total_fee=', $total_fee,PHP_EOL;
    //阶梯扣费
//    print_r($cancel_cost);
//    `cancel_cost` varchar(2000) NOT NULL, /*取消费用
//    二维数组 array(array('c_type'=>类型 0 固定金额 1 百分比,'c_days'=>游玩前分钟,'c_cost'=>费用值))*/
    if (isset($cancel_cost) && !empty($cancel_cost)) {
        //取消费用一维数组 array('提前天数'=>'百分比')
        $conf_arr = json_decode($cancel_cost, true);
        print_r($conf_arr);
        foreach ($conf_arr as $key=>$cancel) {
            $cancel_cost_arr[$cancel['c_days']*60] = $key;
//            $minute_arr[$cancel[$key]] = $cancel['c_minutes'];
        }
        print_r($cancel_cost_arr);
        $minute_arr         = array_keys($cancel_cost_arr);
//        sort($minute_arr);
        echo $minute_diff,'----';
        print_r($minute_arr);
        $min_minute         = min($minute_arr);
        $max_minute         = max($minute_arr);
        echo 'minute_diff=', $minute_diff,PHP_EOL;
        echo 'min_minute=', $min_minute,PHP_EOL;
        echo 'max_minute=', $max_minute,PHP_EOL;
        $fee = 0;
        if ($minute_diff <= $min_minute) {
            $c_type = $conf_arr[$cancel_cost_arr[$min_minute]]['c_type'];
            if ($c_type==1) {
                $fee = $price * $conf_arr[$cancel_cost_arr[$min_minute]]['c_cost'] / 100;
            } else {
                $fee = $conf_arr[$cancel_cost_arr[$min_minute]]['c_cost'];//单位为分
            }
        }
        elseif ($minute_diff >= $max_minute) {
        }
        else {
            $keys = array_keys($minute_arr);
            print_r($keys);
            foreach ($minute_arr as $minute=>$conf_key) {
                $position = array_search($minute, $keys);
                if (isset($keys[$position + 1])) {
                    $keyAfterTwoVal = $keys[$position + 1];
                }

                if ($minute_diff >= $minute && $minute_diff <= $minute_arr[$keyAfterTwoVal]) {
                    $conf_key = $cancel_cost_arr[$minute_arr[$keyAfterTwoVal]];
                    echo 'conf-key=' . $conf_key,PHP_EOL;
                    $c_type = $conf_arr[$conf_key]['c_type'];
                    if ($c_type==1) {
                        $fee = $price * $conf_arr[$conf_key]['c_cost'] / 100;
                    } else {
                        $fee = $conf_arr[$conf_key]['c_cost'];//单位为分
                    }
//                    $fee = $conf_arr[$minute_arr[$keyAfterTwoVal]];
                    break;
                }
            }
        }
        $total_fee += $fee  ;
    }
    echo 'total_fee=', $total_fee,PHP_EOL;
    return $total_fee;
}

var_dump(count_cost_fee_dev(17360, 1200, '2015-05-30'));
exit;



function LogRefund($txt,$file='/var/www/html/new/d/logs/refund_log.txt'){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

function Response( $msg, $status = "fail") {
    $json = '{"status":"'.$status.'", "msg":"'.$msg.'"}';
    exit($json);
}

$ordernum = $_REQUEST['ordernum'];//13
$soap = SoapInit::GetSoapInside();
$xml  = $soap->Order_Globle_Search("", "", "", "", "", "", "", "", "", "", "", "",
    $ordernum, "", "", "", "", "", "", "1", "0", "100", "0", "0",
    "", "0", "", "0", "", "", "", "0", "0");
//echo $xml;//Response;
//exit;
$order_arr = simplexml_load_string($xml);
//print_r($order_arr);Response;
if (!count($order_arr)) {
    LogRefund("[{$ordernum}]|订单号不能为空",LOG_NAME);
    Response("订单不存在。");
}
$aid    = (int)$order_arr->Rec->UUaid;
$sellid = (int)$order_arr->Rec->UUsellid;

//TODO::判断订单状态，未使用，已支付
if ( $order_arr->Rec->UUpaystatus !=1
    || $order_arr->Rec->UUpmode !=1 ) {
    LogRefund(
        "[{$ordernum}]|只有已支付未使用并且是使用支付宝支付的订单方可退款"
        ."|UUstatus={$order_arr->Rec->UUstatus}，UUpaystatus={$order_arr->Rec->UUpaystatus}"
        ."，UUpmode={$order_arr->Rec->UUpmode}",LOG_NAME);
    Response("只有已支付未使用并且是使用支付宝支付的订单方可退款。");
}
//$order_type = 0;
//TODO::判断订单类型
if ($order_arr->Rec->UUpack_order==1) {
    //套票
    $main_order = (string)$order_arr->Rec->UUordernum;
}
elseif ($order_arr->Rec->UUconcat_id>0
    && (string)$order_arr->Rec->UUconcat_id!=(string)$order_arr->Rec->UUordernum)
{
    //联票订单
    $main_order = (string)$order_arr->Rec->UUconcat_id;
}
else {
    //普通订单
}

//退票数，0表示取消订单
$tnum      = intval($_REQUEST['tnum']);
$FeeCost   = 0;//取消费用
$TotalFee  = 0;


if ($tnum == 0 ) {
    //取消订单
    $subject   = "取消订单退款({$ordernum})";
    $TotalFee  = (int)$order_arr->Rec->UUtprice * (int)$order_arr->Rec->UUtnum;
    //一张票的取消费用
    $FeeCost   = count_cost_fee(
        (int)$order_arr->Rec->UUtid,
        (int)$order_arr->Rec->UUtprice,
        (string)$order_arr->UUbegintime
    );
    //TODO::获取这个订单的票数
    $sql = "SELECT pre_num FROM pft_order_num_modify WHERE orderid='$ordernum' ORDER BY id ASC limit 1";
    $GLOBALS['le']->query($sql);
    $GLOBALS['le']->fetch_assoc();
    $preNum   = $GLOBALS['le']->f('pre_num');
    $FeeCost  = $preNum ? $preNum * $FeeCost : (int)$order_arr->Rec->UUtnum * $FeeCost;//所有票数的取消费用
    $TotalFee_tmp = $TotalFee - $FeeCost;//原订单总金额-取消费用
    $TotalFee = $TotalFee_tmp < 0 ? 0 : $TotalFee_tmp;
}
elseif ($tnum>=1 ) {
//    $curTnum = (int)$order_arr->Rec->UUtnum;
    //&& $tnum < $order_arr->UUtnum
    //修改票数，退款金额=下单时的价格 * 票数
//    echo $preNum,'++',(int)$order_arr->Rec->UUtnum,'++',$tnum;

    //TODO::获取这个订单的票数
    $sql = "SELECT `pre_num`,`done_num` FROM pft_order_num_modify WHERE orderid='$ordernum' ORDER BY id DESC limit 1";
    $GLOBALS['le']->query($sql);
    $GLOBALS['le']->fetch_assoc();
    $preNum   = $GLOBALS['le']->f('pre_num');
    $doneNum  = $GLOBALS['le']->f('done_num');
    $TotalFee = $order_arr->Rec->UUtprice * ($preNum - $doneNum);
//    echo $TotalFee;
//    exit;
//    $TotalFee = $order_arr->Rec->UUtprice * ((int)$order_arr->Rec->UUtnum - $tnum);
    $subject  = "修改订单退款({$ordernum})";
}
else {
    LogRefund("[{$ordernum}]|修改票数不能超过下单时的票数",LOG_NAME);
    Response ("修改票数不能超过下单时的票数");
}

//TODO::获取交易号
$trade_ordernum = isset($main_order) ? $main_order : $ordernum;
$sql = "SELECT trade_no,sourceT FROM pft_alipay_rec WHERE out_trade_no='$trade_ordernum' AND trade_no<>'' LIMIT 1";
$GLOBALS['le']->query($sql);
$GLOBALS['le']->fetch_assoc();
$trade_no = $GLOBALS['le']->f('trade_no');
$sourceT  = $GLOBALS['le']->f('sourceT');//支付方式，0支付宝1微信支付
if (!$trade_no) {
    LogRefund("[{$trade_ordernum}]交易号不存在{$sql}",LOG_NAME);
    Response("交易号不存在");
}
$TopAid = $aid;
if ($order_arr->Rec->UUaids!=0) {
    $aids = explode(',', (string)$order_arr->Rec->UUaids);
    $TopAid = $aids[0];
    $BtmAid = $aids[count($aids)-1];
}

if ($tnum==0 && $FeeCost>0 && $order_arr->Rec->UUaids!=0) {
//    sleep(1);
    //最顶级供应商加手续费
    $res = $soap->PFT_Member_Fund_Modify($TopAid, 0, $FeeCost, ACTION_MONEY_ADD, 0, null,0, 2,$ordernum);
    LogRefund("{$ordernum}|最顶级供应商($TopAid)加手续费返回结果：{$res}",LOG_NAME);
    //最底级供应商扣手续费
    $res = $soap->PFT_Member_Fund_Modify($BtmAid, 0, $FeeCost, ACTION_MONEY_CUT, 0,null,0, 2,$ordernum);
    LogRefund("{$ordernum}|最底级供应商($BtmAid)扣手续费：{$res}",LOG_NAME);
}

//$TopAid = !isset($TopAid) ? $aid : $TopAid;
//$BtmAid = !isset($BtmAid) ? $aid : $BtmAid;
//LogRefund($sql, LOG_NAME);
//if ($aid != $TopAid) {
//TODO::非直销订单，写退款记录，aid为上级供应商ID；由于支付宝退款成功后还写退款记录，若这里不做判断，记录会重复。
$sql = "INSERT INTO pft_member_alipay(fid,orderid,total_fee,money,rectime,daction,dtype)";
$sql .= " VALUES($aid, '$ordernum',$TotalFee,$TotalFee,now(),1,1)";
LogRefund("[{$trade_ordernum}]退款记录{$sql}",LOG_NAME);
$GLOBALS['le']->query($sql);
//}


//$sql = "SELECT refund_back FROM pft_member_extinfo WHERE fid={$TopAid} LIMIT 1";
//$GLOBALS['le']->query($sql);
//$GLOBALS['le']->fetch_assoc();
//if ($GLOBALS['le']->f('refund_back')==1) {
//退款当天日期，必填，格式：年[4位]-月[2位]-日[2位] 小时[2位 24小时制]:分[2位]:秒[2位]，如：2007-10-01 13:13:13
$refund_date = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
//TODO::记录支付宝退款记录
$sql  = <<<SQL
INSERT INTO pft_order_refund(aid, ordernum,refund_num,refund_money,refund_fee,refund_time,trade_no,subject,sourceT)
VALUES($TopAid, $trade_ordernum, $tnum, $TotalFee,$FeeCost, '$refund_date','$trade_no','$subject', $sourceT)
SQL;
$GLOBALS['le']->query($sql);
//}
//$total_fee_yuan = $fee_cost / 100;
//TODO::微信发送通知
define('DEFAULT_WECHAT_APPID', 'wxd72be21f7455640d');//票付通公众号
include '/var/www/html/wx/wechat/iwx.php';
//if ($_SERVER['REQUEST_TIME']<strtotime('2015-02-16 00:00:00')) {
//    $wx_open_id = 'oNbmEuGRtiN4dpSUa4EnKtijHuQc';//通知财务-陈琼容
//} else {
//    $wx_open_id = 'oNbmEuCJxEEnEbfrsdYhbDKxp9LY';//通知财务-宋姐
//}
$wx_open_id = 'oNbmEuGRtiN4dpSUa4EnKtijHuQc';//通知财务-陈琼容
$TotalFee = $TotalFee / 100;
$data        = array(
    'first'     => array('value'=>'不妙，有客户申请退款啦！','color'=>'#173177'),
    'reason'    => array('value'=>'取消订单退款','color'=>'#173177'),
    'refund'    => array('value'=> $TotalFee . 'RMB','color'=>'#ff0000'),
    'remark'    => array('value'=> "订单号：{$trade_ordernum}",'color'=>'#ff6600'),
);

$msgRet = TemplateMessage::sendTemplateMessage($data,
    $wx_open_id, TemplateMessage::CANCEL_ORDER,
    "http://wx.12301.cc/html/order_detail.html?fromt=f542e9fac6e76f4b3b66422d49e5585c&ordernum={$ordern}",
    '#FF0000');

LogRefund("[{$ordernum}]{$subject}成功",LOG_NAME_OK);
Response("success", "ok");